import 'package:bruno/bruno.dart';
import 'package:countdown/common/utils/utils.dart';
import 'package:countdown/common/values/values.dart';
import 'package:countdown/page/application/widget/SidebarMenu.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_lunar_datetime_picker/date_init.dart';
import 'package:flutter_lunar_datetime_picker/flutter_lunar_datetime_picker.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:lunar/calendar/Lunar.dart';
import 'package:shrink_sidemenu/shrink_sidemenu.dart';
import '../list/widget/PopupMenu.dart';
import 'index.dart';

///事件页面
class EventPage extends GetView<EventController> {
  const EventPage({super.key});

  //事件
  @override
  Widget build(BuildContext context) {
    ButtonPanelConfig buttonPanelConfig = controller.state.buttonPanelConfig;

    var lable = controller.state.lable;
    var dateLable = controller.state.dateLable;

    BrnAppBar _buildAppBar() {
      return BrnAppBar(
          backgroundColor: AppColors.primaryBackground,
          //默认显示返回按钮
          automaticallyImplyLeading: false,
          brightness: Brightness.light,
          title:
              '${!controller.state.edit ? "新建" : "编辑"}${buttonPanelConfig.name}',
          leading: Padding(
            padding: EdgeInsets.symmetric(
              horizontal: 10.w,
            ),
            child: IconButton(
              icon: Icon(
                CupertinoIcons.xmark,
                size: 24.sp,
              ),
              onPressed: () {
                controller.empty();
                Get.back();
              },
            ),
          ),
          //自定义的右侧文本
          actions: Padding(
            padding: const EdgeInsets.only(right: 0),
            child: IconButton(
              icon: Icon(
                CupertinoIcons.check_mark,
                size: 24.sp,
              ),
              onPressed: () {
                !controller.state.edit
                    ? controller.save()
                    : controller.updateEvent();
                Get.back();
              },
            ),
          ));
    }

    Widget _buildAddFrom(BuildContext context) {
      return Obx(() => Column(children: [
            Container(
              margin: EdgeInsets.symmetric(horizontal: 20.sp, vertical: 28.sp),
              alignment: Alignment.center,
              height: 220.sp,
              decoration: const BoxDecoration(
                color: Colors.white, //shape 设置边，可以设置圆角
                borderRadius: BorderRadius.all(Radius.circular(20.0)),
              ),
              child: Column(
                children: [
                  Container(
                    margin: EdgeInsets.only(
                        left: 20.sp, right: 20.sp, top: 20.sp, bottom: 0),
                    height: 42.h,
                    child: Row(
                      mainAxisSize: MainAxisSize.min,
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Expanded(
                          child: TextField(
                            controller: TextEditingController()
                              ..text = '${buttonPanelConfig.emoji}',
                            style: TextStyle(
                                fontSize: 28.sp,
                                color: Colors.black,
                                fontWeight: FontWeight.w500),
                            decoration: InputDecoration(
                              hintStyle: TextStyle(
                                  fontSize: 16.sp,
                                  color: Colors.black,
                                  fontWeight: FontWeight.w500),
                              border: InputBorder.none,
                            ),

                            showCursor: false,
                            readOnly: true, // 禁用唤起系统键盘
                          ),
                        ),
                        SizedBox(
                          width: 50.w,
                          child: IconButton(
                              onPressed: () {
                                controller.openKeyWord(context);
                              },
                              icon: Icon(
                                Icons.tag_faces_outlined,
                                color: Colors.grey,
                                size: 32.sp,
                              )),
                        ),
                      ],
                    ),
                  ),
                  Padding(
                    padding: EdgeInsets.only(
                        left: 20.sp, right: 20.sp, top: 4.sp, bottom: 4.sp),
                    child: Divider(
                      color: Colors.grey[300],
                      height: 1.3,
                    ),
                  ),
                  Container(
                    margin: EdgeInsets.only(
                        left: 20.sp, right: 20.sp, top: 20.sp, bottom: 0),
                    height: 42.h,
                    child: TextField(
                      inputFormatters: [
                        LengthLimitingTextInputFormatter(15),
                      ],
                      controller: TextEditingController.fromValue(
                          TextEditingValue(
                              // 设置内容
                              text: controller.state.title,
                              // 保持光标在最后
                              selection: TextSelection.fromPosition(
                                  TextPosition(
                                      affinity: TextAffinity.downstream,
                                      offset: controller.state.title.length)))),
                      style: TextStyle(
                          fontSize: 28.sp,
                          color: Colors.black,
                          fontWeight: FontWeight.w500),
                      decoration: InputDecoration(
                        hintText:
                            "${lable[buttonPanelConfig.value.toString()]}",
                        hintStyle: TextStyle(
                            fontSize: 22.sp,
                            color: Colors.black.withOpacity(0.3),
                            fontWeight: FontWeight.w500),
                        border: InputBorder.none,
                      ),
                      onSubmitted: (value) {
                        controller.state.title = value;
                        controller.state.cardTitle = value;
                      },
                      //ios自带键盘会输入字母。等用户确认再更新 onChanged: (value) {
                      //   controller.state.title = value;
                      //   controller.state.cardTitle = value;
                      // },
                      showCursor: false,
                    ),
                  ),
                  Padding(
                    padding:
                        EdgeInsets.only(left: 20, right: 20, top: 4, bottom: 4),
                    child: Divider(
                      color: Colors.grey[300],
                      height: 1.3,
                    ),
                  ),
                  Container(
                    margin: EdgeInsets.only(
                        left: 20.sp, right: 20.sp, top: 20.sp, bottom: 0),
                    height: 38.h,
                    child: TextField(
                      controller: TextEditingController()
                        ..text = formatDateDay(controller.state.date,
                            lunar: controller.state.lunar),
                      style: const TextStyle(
                          fontSize: 22,
                          color: Colors.black,
                          fontWeight: FontWeight.w500),
                      decoration: InputDecoration(
                        hintText: "${dateLable[buttonPanelConfig.value]}",
                        hintStyle: TextStyle(
                            fontSize: 22.sp,
                            color: Colors.black.withOpacity(0.3),
                            fontWeight: FontWeight.w500),
                        border: InputBorder.none,
                      ),
                      onTap: () {
                        DatePicker.showDatePicker(
                          context,
                          lunarPicker: false,
                          dateInitTime: DateInitTime(
                              currentTime: DateTime.now(),
                              maxTime: DateTime(2038, 12, 12),
                              minTime: DateTime(1968, 3, 4)),
                          onConfirm: (time, luanr) {
                            //debugPrint("${time.toString()}是否阴历$luanr");
                            controller.state.date = time;
                            controller.state.lunar = luanr;
                          },
                          onChanged: (time, lunar) {
                            //debugPrint("change:${time.toString()}");
                          },
                        );
                      },
                      showCursor: false,
                      readOnly: true, // 禁用唤起系统键盘
                      //显示光标
                    ),
                  ),
                ],
              ),
            ),
          ]));
    }

    Widget _buildCard() {
      return Obx(() => Container(
            padding: EdgeInsets.symmetric(vertical: 20),
            alignment: Alignment.center,
            height: 250.h,
            width: MediaQuery.of(context).size.width,
            color: AppColors.primaryElement.withOpacity(0.2),
            child: Container(
              width: 180.w,
              margin: EdgeInsets.symmetric(horizontal: 0, vertical: 12.h),
              decoration: const BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.all(Radius.circular(18)),
              ),
              child: Column(
                mainAxisAlignment: MainAxisAlignment.start,
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Row(
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      Container(
                          padding: EdgeInsets.only(
                              left: 10.sp, top: 12.sp, bottom: 4.sp),
                          child: RichText(
                              text: TextSpan(children: <TextSpan>[
                            TextSpan(
                                text: "${buttonPanelConfig.emoji}",
                                style: TextStyle(
                                  fontSize: 26.sp,
                                )),
                          ]))),
                    ],
                  ),
                  Row(
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      Container(
                          padding: EdgeInsets.only(
                              left: 10.sp, top: 4.sp, bottom: 4.sp),
                          child: RichText(
                              text: TextSpan(children: <TextSpan>[
                            TextSpan(
                                text: "${controller.state.cardTitle}",
                                style: TextStyle(
                                    fontSize: 18.sp, color: Colors.black)),
                          ]))),
                    ],
                  ),
                  Row(
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      Container(
                          padding: EdgeInsets.only(
                              left: 10.sp, top: 4.sp, bottom: 4.sp),
                          child: RichText(
                              text: TextSpan(children: <TextSpan>[
                            TextSpan(
                                text: formatDateDay(controller.state.date,
                                    lunar: controller.state.lunar),
                                style: TextStyle(
                                    fontSize: 14.sp, color: Colors.black)),
                          ]))),
                    ],
                  ),
                  Row(
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      Container(
                          padding: EdgeInsets.only(
                              left: 10.sp, top: 2, bottom: 4.sp),
                          child: RichText(
                              text: TextSpan(children: <TextSpan>[
                            TextSpan(
                                text: format(controller.state.dayBetween),
                                style: TextStyle(
                                    fontSize: 18.sp, color: Colors.black)),
                            // const TextSpan(
                            //     text: " 天",
                            //     style: TextStyle(
                            //         fontSize: 16, color: Colors.black))
                          ]))),
                    ],
                  ),
                ],
              ),
            ),
          ));
    }

    return Scaffold(
      //解决键盘顶起元素
      resizeToAvoidBottomInset: false,
      backgroundColor: AppColors.primaryBackground,
      body: Column(
        children: <Widget>[
          _buildAppBar(),
          _buildCard(),
          _buildAddFrom(context),
          const Spacer(),
        ],
      ),
    );
  }
}

/// <summary>
/// todo: 保持光标在最后
/// author: zwb
/// date: 2021/7/19 11:43
/// param: 参数
/// return: void
/// <summary>
///
lastCursor({required TextEditingController textEditingController}) {
  /// 保持光标在最后
  final length = textEditingController.text.length;
  textEditingController.selection =
      TextSelection(baseOffset: length, extentOffset: length);
}
